package com.xuxk.project.oauth.controller.rpc;

import com.alibaba.nacos.common.utils.Md5Utils;
import com.xuxk.project.oauth.annotation.OauthLog;
import com.xuxk.project.oauth.config.JwtUtil;
import com.xuxk.project.oauth.service.RedisService;
import com.xuxk.project.util.ErrorCodeException;
import com.xuxk.project.util.JwtBaseInfo;
import com.xuxk.project.util.UUIDGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 认证服务接口
 * @author 许孝康
 * @date 2020/8/3
 * @company 橙云科技有限公司
 */
@RequestMapping("/rpc/oauth")
@RestController
public class OauthController {

    @Resource
    private JwtUtil jwtUtil;

    @Value("${oauth.token.secretKey}")
    private String secretKey;

    @Value("${oauth.token.tokenExpireTime}")
    private long tokenExpireTime;

    @Autowired
    RedisService redisService;


    @GetMapping(value = "/getToken",produces = MediaType.APPLICATION_JSON_VALUE)
    @OauthLog(eventName = "获取认证码")
    public String getToken(String serverName,String loginAccout){

        JwtBaseInfo info = new JwtBaseInfo();
        info.setServerName(serverName);
        info.setLoginAccout(loginAccout);
        info.setUuid(UUIDGenerator.getUUID());
        String token = jwtUtil.buildJWT(info, secretKey, tokenExpireTime);

        if(StringUtils.isBlank(token)){
            throw new ErrorCodeException("token获取失败！");
        }
        //将token放入redis中
        String key = Md5Utils.getMD5(token,"UTF-8");
        redisService.vset(key,token,tokenExpireTime);

        return token;
    }
}
